package com.cwt_taxi_xa.protocol;

import com.cwt_taxi_xa.MainApplication;
import com.cwt_taxi_xa.constants.MyStatus;
import com.cwt_taxi_xa.util.AppLog;
import com.cwt_taxi_xa.util.ExceptionUtil;
import com.cwt_taxi_xa.util.StringUtil;
import com.cwt_taxi_xa.util.Tools;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.FixedReceiveBufferSizePredictorFactory;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;


/**
 * @author zr
 * socket连接通讯平台
 */
public class DispatchCenterClient {

	private static final String TAG = "DispatchCenterClient";
	/**
	 * 初始化连接
	 */
	public static void init() {
		DispatchCenterUsers.bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(
				Executors.newCachedThreadPool(),
				Executors.newCachedThreadPool()));
		DispatchCenterUsers.bootstrap.setOption("receiveBufferSizePredictorFactory", new FixedReceiveBufferSizePredictorFactory(655350));
		DispatchCenterClientPipelineFactory cpcf = new DispatchCenterClientPipelineFactory();
		DispatchCenterUsers.bootstrap.setPipelineFactory(cpcf);

		DispatchCenterUsers.bootstrap.setOption("tcpNoDelay", true);
		DispatchCenterUsers.bootstrap.setOption("keepAlive", true);
		DispatchCenterUsers.bootstrap.setOption("reuseAddress", true);
	}

	/**
	 * 创建连接
	 * @param type 1 自动 2 手动
	 */
	public static long lastconnect = 0;
	public static void connect(int type) {
		//modify by undi 5*60*1000->3*60*1000
		if(System.currentTimeMillis()-lastconnect < 1 *60*1000){
			AppLog.e(TAG,"connect Within 1 minutes return!");
			return;
		}else{
			lastconnect = System.currentTimeMillis();
		}

		DispatchCenterUsers.connectionMode = type;

		if(DispatchCenterUsers.bootstrap==null){
			init();
		}

		String ip = null;
		String port = null;

		try {
			int hytdswitch = DeviceBiz.getSwitcher();
			//判断主服务器是否打开，如果主服务器关闭怎获取备用服务器
			if(hytdswitch == 1){
				ip = DeviceBiz.getIp();
				port = DeviceBiz.getPort();
			}else{
				//判断副服务器是否打开，如果副服务器打开，用付服务器
				int hytdswitchBak = DeviceBiz.getSwitcherBak();
				if(hytdswitchBak == 1){
					ip = DeviceBiz.getIpBak();
					port = DeviceBiz.getPortBak();
				}
			}

			//判断IP为域名，还是IP
			if(!StringUtil.isNull(ip)){
				boolean isip = Tools.isIp(ip);
				if(!isip){
					//非IP进行域名转换成IP
					ip = Tools.domainToip(ip);
				}
			}

		} catch (Exception e) {
			AppLog.e(ExceptionUtil.getInfo(e));
			e.printStackTrace();
		}

		AppLog.i("【通讯平台】Client: 连接调度中心:"+ip+",端口:"+port);
		AppLog.savelog("【通讯平台】Client: 连接调度中心:"+ip+",端口:"+port);
		if(!StringUtil.isNull(ip) && !StringUtil.isNull(port)){
			try {
				/**向目标地址发起一个连接*/
				DispatchCenterUsers.channelFuture = DispatchCenterUsers.bootstrap.connect(new InetSocketAddress(ip, Integer.parseInt(port)));
				DispatchCenterUsers.channel = DispatchCenterUsers.channelFuture.getChannel();
				// 等待链接成功，成功后发起的connected事件将会使handler开始发送信息并且等待messageRecive
				DispatchCenterUsers.channelFuture.awaitUninterruptibly();
			} catch (Exception e) {
				AppLog.i("【通讯平台】Client: 连接调度中心:"+ip+",端口:"+port+"失败"+e.getMessage());
				AppLog.savelog("【通讯平台】Client: 连接调度中心:"+ip+",端口:"+port+"失败"+e.getMessage());
				DispatchCenterUsers.isConnTimer = false;
				MyStatus.center = false;
				if(MainApplication.topActivity!=null){
					MainApplication.topActivity.setStatus(2, false);
				}
				AppLog.e(ExceptionUtil.getInfo(e));
				e.printStackTrace();
			}
			if(DispatchCenterUsers.channelFuture!=null){
				if(DispatchCenterUsers.channelFuture.isSuccess()){
					AppLog.i("【通讯平台】Client: 连接成功！");
					AppLog.savelog("【通讯平台】Client: 连接成功！");
					DispatchCenterUsers.isConnTimer = true;
					MyStatus.center = true;
					if(MainApplication.topActivity!=null){
						MainApplication.topActivity.setStatus(2, true);
					}
					//启动定时抓拍
					BusinessProcessSZ.photographTask.startThread();
				}else{
					AppLog.i("【通讯平台】Client: 连接失败！");
					AppLog.savelog("【通讯平台】Client: 连接失败！");
					DispatchCenterUsers.isConnTimer = false;
					MyStatus.center = false;
					if(MainApplication.topActivity!=null){
						MainApplication.topActivity.setStatus(2, false);
					}
				}
			}
		}else{
			MyStatus.center = false;
			MainApplication.topActivity.setStatus(2, false);
			AppLog.e("【通讯平台】Client: 连接调度中心失败:IP或端口为空");
			AppLog.savelog("【通讯平台】Client: 连接调度中心失败:IP或端口为空");
		}

	}

	/**
	 * 断开连接
	 */
	public static void disconnect() {
		try {
			DispatchCenterUsers.channelFuture.awaitUninterruptibly();
			if (!DispatchCenterUsers.channelFuture.isSuccess()) {
				DispatchCenterUsers.channelFuture.getCause().printStackTrace();
			}
			DispatchCenterUsers.channelFuture.getChannel().getCloseFuture().awaitUninterruptibly();
			DispatchCenterUsers.bootstrap.releaseExternalResources();
		} catch (Exception e) {
			AppLog.e(ExceptionUtil.getInfo(e));
			e.printStackTrace();
		}
	}

}
